package com.shuzi.MediaShare.download;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.shuzi.MediaShare.R;
import com.shuzi.MediaShare.download.DownloadMangerAdapter.ViewHolder;
import com.shuzi.MediaShare.gui.DetailViewPagerAdapter;
import com.shuzi.MediaShare.utils.Logger;
import com.shuzi.MediaShare.utils.Util;
import com.viewpagerindicator.UnderlinePageIndicator;

/**
 * 下载管理界面
 * 
 * @author lung 下午8:14:25 2013
 */
public class DownloadManagerActivity extends Activity
{

	/** 下载管理器 */
	private DownloadManager downloadManager;

	private ViewPager viewPager;

	private DetailViewPagerAdapter adapter;

	private DownloadMangerAdapter downloadMangerAdapter;

	private LocalFileAdapter localFileAdapter;

	private ListView downingListView = null;

	private ListView localMovieListView = null;

	// private Handler handler = new Handler();

	private List<DownloadInfo> allDownloadInfos;

	private Logger logger;

	private UnderlinePageIndicator underlinePageIndicator;

	private LinearLayout backButton;

	private ArrayList<File> files;

	private TextView downloadTextView;

	private TextView localFileTextView;

	private Handler handler;

	private DownloadListener downloadListener = new DownloadListener()
	{

		@Override
		public void onTaskCountChanged(int state, DownloadInfo info)
		{
			if (downloadMangerAdapter != null)
			{
				downloadMangerAdapter.notifyDataSetChanged();

			}

		}

		@Override
		public void onStateChange(int state, final DownloadInfo info)
		{
			logger.v("Download", "DownloadManager ---state= " + state + "");

			if (state == DownloadInfo.STATE_FINISH)
			{
				DownloadManagerActivity.this.runOnUiThread(new Runnable()
				{

					@Override
					public void run()
					{
						logger.v("lung", " DownloadInfo.STATE_FINISH");
						refreshListView(info);
						refreshLocaFile();

					}
				});
				handler.postDelayed(new Runnable()
				{

					@Override
					public void run()
					{
						downloadManager.deleteDownloadInfo(info);
					}
				}, 1000);
			}
		}

		@Override
		public void onProgress(int percent, DownloadInfo info)
		{
			logger.v("Download", "DownloadManager ---percent= " + percent + "");
			refreshListView(info);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.download_manager);

		init();
	}

	@Override
	protected void onDestroy()
	{
		if (downloadManager != null)
		{
			downloadManager.unRegisterDownloadListener(downloadListener);
		}
		super.onDestroy();
	}

	/**
	 * 初始化
	 */
	private void init()
	{
		handler = new Handler();
		logger = Logger.getLogger();
		viewPager = (ViewPager) findViewById(R.id.download_manager_viewPager);
		underlinePageIndicator = (UnderlinePageIndicator) findViewById(R.id.underlinePageIndicator1);
		downloadManager = DownloadManager.getInstace();
		allDownloadInfos = downloadManager.getAllDownloadInfos();

		adapter = new DetailViewPagerAdapter(getDetailViewList());
		downloadMangerAdapter = new DownloadMangerAdapter(this,
				allDownloadInfos);
		viewPager.setAdapter(adapter);
		underlinePageIndicator.setViewPager(viewPager);
		underlinePageIndicator.setSelectedColor(Color.GRAY);
		downingListView.setAdapter(downloadMangerAdapter);
		downingListView.setCacheColorHint(0);
		files = new ArrayList<File>();
		localFileAdapter = new LocalFileAdapter(this, files);
		localMovieListView.setAdapter(localFileAdapter);
		localMovieListView.setCacheColorHint(0);
		downloadManager.registerDownloadListener(downloadListener);
		registerForContextMenu(downingListView);
		backButton = (LinearLayout) findViewById(R.id.backButton);
		backButton.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				finish();

			}
		});
		refreshLocaFile();
		localMovieListView.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id)
			{
				Intent it = new Intent(Intent.ACTION_VIEW);
				it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				Uri uri = Uri.parse(files.get(position).getPath());
				it.setDataAndType(uri, "video/mp4");
				startActivity(it);
			}
		});
		localMovieListView
				.setOnItemLongClickListener(new OnItemLongClickListener()
				{

					@Override
					public boolean onItemLongClick(AdapterView<?> parent,
							View view, int position, long id)
					{
						// Toast.makeText(DownloadManagerActivity.this,
						// "position = " + position, Toast.LENGTH_SHORT)
						// .show();
						deleteLocalFile(files.get(position));
						return true;
					}
				});

		downingListView.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id)
			{

				if (allDownloadInfos.get(position).getState() == DownloadInfo.STATE_DOWNLOADING)
				{
					downloadManager.stopDownloadInfo(allDownloadInfos
							.get(position));
				} else if (allDownloadInfos.get(position).getState() == DownloadInfo.STATE_ERROR
						|| allDownloadInfos.get(position).getState() == DownloadInfo.STATE_STOP)
				{
					downloadManager.restartDownloadInfo(allDownloadInfos
							.get(position));
				}

			}
		});
		downloadTextView = (TextView) findViewById(R.id.download_text);
		localFileTextView = (TextView) findViewById(R.id.local_file_text);
		downloadTextView.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				if (viewPager != null)
				{
					viewPager.setCurrentItem(0);
				}

			}
		});
		localFileTextView.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				if (viewPager != null)
				{
					viewPager.setCurrentItem(1);
				}

			}
		});
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo)
	{
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.add(0, 0, 0, "删除下载任务");
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item)
	{
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		int position = (int) info.id;
		switch (item.getItemId())
		{
		// 删除
		case 0:
			Toast.makeText(
					this,
					"删除下载任务"
							+ downloadManager.getAllDownloadInfos()
									.get(position).getName(),
					Toast.LENGTH_SHORT).show();
			downloadManager.deleteDownloadInfo(downloadManager
					.getAllDownloadInfos().get(position));

			return true;
		}
		return super.onMenuItemSelected(featureId, item);

	}

	/**
	 * 获取详情分类视图
	 * 
	 * @return
	 */
	private List<View> getDetailViewList()
	{
		List<View> list = new ArrayList<View>();
		downingListView = new ListView(this);
		localMovieListView = new ListView(this);
		list.add(downingListView);
		list.add(localMovieListView);

		return list;
	}

	/**
	 * 刷新本地视频
	 */
	public void refreshLocaFile()
	{
		if (localFileAdapter == null)
		{
			return;
		}
		logger.v("lung", "refreshLocaFile");
		ArrayList<File> nowFiles = Util.searchFile(
				downloadManager.getBasePath(), DownloadInfo.MP4);
		if (nowFiles != null)
		{
			files.clear();
			files.addAll(nowFiles);
		}
		localFileAdapter.notifyDataSetChanged();

	}

	/**
	 * 刷新进度
	 * 
	 * @param percent
	 * @param info
	 */
	public synchronized void refreshListView(final DownloadInfo info)
	{
		if (allDownloadInfos.size() == 0)
		{
			return;
		}
		{

		}
		int firstPositon = downingListView.getFirstVisiblePosition();
		int lastPosition = downingListView.getLastVisiblePosition();
		for (int i = firstPositon; i <= lastPosition; i++)
		{

			if (allDownloadInfos.get(i).getKey().equals(info.getKey()))
			{
				View view = downingListView.getChildAt(i - firstPositon);
				downloadMangerAdapter.refreshData((ViewHolder) view.getTag(),
						info);
				return;

			}
		}
	}

	/**
	 * 删除本地文件
	 * 
	 * @param file
	 */
	public void deleteLocalFile(final File file)
	{
		AlertDialog.Builder bui = new Builder(this);
		bui.setMessage("是否删除" + file.getName());
		bui.setTitle("温馨提示！");

		bui.setPositiveButton("确定", new DialogInterface.OnClickListener()
		{

			public void onClick(DialogInterface dialog, int which)
			{
				if (file.exists())
				{
					if (file.delete())
					{
						refreshLocaFile();
					}
				}

			}
		});
		bui.setNegativeButton("取消", null);
		bui.show();// 如果要显示对话框，一定要加上这句
	}

}
